/*
 * Copyright (C) 2003, Velocityme Partnership
 * VelocitymeTag.java
 *
 * Created on 22 December 2004, 11:50
 */

package com.velocityme.www.tag;

import com.velocityme.entity.Node;
import com.velocityme.session.KeyLocal;
import com.velocityme.session.NodeLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 *
 * @author  Robert
 */
public class MarkupTag extends BodyTagSupport {

    @Override
    public int doAfterBody() throws JspTagException {
        BodyContent bc = getBodyContent();
        String bodyString = bc.getString();
        bc.clearBody();
        // remove whitespace from start
        bodyString = bodyString.replaceAll("^\\s+", "");
        // remove whitespace from end
        bodyString = bodyString.replaceAll("\\s+$", "");
        // replace carriage returns with <br/>
        bodyString = bodyString.replaceAll("\n","<br/>");
        // markup urls to put them inside a link
        String urlRegex = "\\b((https?|telnet|gopher|file|wais|ftp) : \n [\\w/\\#~:.?+=&%@!\\-] +?)\n(?=[.:?\\-] *(?: [^\\w/\\#~:.?+=&%@!\\-]| $))";
        Pattern p = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE + Pattern.COMMENTS);
        Matcher m = p.matcher(bodyString);
        bodyString = m.replaceAll("<a href=\"$1\" target=\"xyz\">$1</a>");
        // markup email addresses to make them mailto
        String urlRegex2 = "\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b";
        Pattern p2 = Pattern.compile(urlRegex2, Pattern.CASE_INSENSITIVE + Pattern.COMMENTS);
        Matcher m2 = p2.matcher(bodyString);
        bodyString = m2.replaceAll("<a href=\"mailto:$0\">$0</a>");
        // markup node links
        String urlRegex3 = "\\bnode:(\\d+)\\b";
        Pattern p3 = Pattern.compile(urlRegex3, Pattern.CASE_INSENSITIVE + Pattern.COMMENTS);
        Matcher m3 = p3.matcher(bodyString);
        try {
            HttpSession session = pageContext.getSession();
            KeyLocal key = (KeyLocal)session.getAttribute("sessionKey");
            StringBuffer sb = new StringBuffer();
            while (m3.find()) {
                Long nodeId = Long.decode(m3.group(1));
                Node node = lookupNodeBean().findNode(key, nodeId);
                StringBuffer sb2 = new StringBuffer();
                sb2.append("<a href=\"./showNode.do?nodeId=");
                sb2.append(node.getId());
                sb2.append("\">");
                sb2.append(node.getClass().toString());
                sb2.append(" (");
                sb2.append(node.getName());
                sb2.append(")</a>");
                m3.appendReplacement(sb, sb2.toString());
            }
            m3.appendTail(sb);
            bodyString = sb.toString();
        } catch(Exception e) {
            throw new JspTagException("Exception: " + e.getMessage());
        }
        try {
            getPreviousOut().print(bodyString);
        }
        catch(java.io.IOException e) {
            throw new JspTagException("IO Error: " + e.getMessage());
        }
        return EVAL_PAGE;
    }

    private NodeLocal lookupNodeBean() {
        try {
            Context c = new InitialContext();
            return (NodeLocal) c.lookup("java:comp/env/NodeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
